﻿using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using YJ_Code.Entities.Topic;
using YJ_Code.Enums;
using YJ_Code.Tool;
using YJ_Core.Entities.Utils;
using YJ_Core.Tool.Token;
using static YJ_App.Admin_System.Dtos.SensitiveWordsDto;

namespace YJ_App.Admin_System.Service
{
    /// <summary>
    /// 敏感词管理
    /// </summary>
    [ApiDescriptionSettings(ApiGroupEnumsCode.SensitiveWords, Name = "SensitiveWordsService")]
    public class SensitiveWordsAdmin : IDynamicApiController, ITransient
    {
        /// <summary>
        /// sql
        /// </summary>
        private readonly ISqlSugarClient _db;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db"></param>
        public SensitiveWordsAdmin(ISqlSugarClient db)
        {
            _db = db;
        }

        /// <summary>
        /// 添加敏感词
        /// </summary>
        /// <returns></returns>
        public async Task<ResponseStatus> AddSensitiveWords(AddSensitiveWordsInput input)
        {
            //去掉入参前后空格
            ToolHelper.TrimStrings(input);

            if (string.IsNullOrWhiteSpace(input.Word))
            {
                throw Oops.Bah("请输入敏感词");
            }

            // 获取操作用户的信息
            var user = TokenService.GetClaimKey() ?? throw Oops.Bah("未登录，无权限访问接口");

            int count = await _db.Insertable(new SensitiveWords
            {
                Word = input.Word,
                CreateMan = user.UserName,
                CreateTime = DateTime.Now,
                Id = Guid.NewGuid().ToString("N"),
                IsDelete = false,
                IsEnabled = input.IsEnabled,

            }).ExecuteCommandAsync();

            if (count < 1)
            {
                throw Oops.Bah("添加失败");
            }

            return new ResponseStatus { Message = "success", StatusCode = 200 };
        }

        /// <summary>
        /// 敏感词列表
        /// </summary>
        /// <returns></returns>
        public async Task<SelectSensitiveWordsListResp> SelectSensitiveWordsList(SelectSensitiveWordsListInput input)
        {
            //去掉入参前后空格
            ToolHelper.TrimStrings(input);

            // 获取操作用户的信息
            var user = TokenService.GetClaimKey() ?? throw Oops.Bah("未登录，无权限访问接口");

            RefAsync<int> total = 0;
            var list = await _db.Queryable<SensitiveWords>()
                .WhereIF(!string.IsNullOrWhiteSpace(input.KeyWord), (t1) => t1.Id.Contains(input.KeyWord) || t1.Word.Contains(input.KeyWord))
                .Select((t1) => new SelectSensitiveWordsListOutput
                {
                    Id = t1.Id,
                    IsEnabled = t1.IsEnabled,
                    Word = t1.Word,
                    CreateTime = t1.CreateTime
                })
                .OrderByDescending(x => x.CreateTime)
                .ToPageListAsync(input.Page, input.PageSize, total);

            return new SelectSensitiveWordsListResp
            {
                List = list,
                Total = total,
                StatusCode = 200,
                Message = "success"
            };
        }

        /// <summary>
        /// 设置敏感词是否启用
        /// </summary>
        /// <returns></returns>
        public async Task<ResponseStatus> SetSensitiveWordsIsEnabled(SetSensitiveWordsIsEnabledInput input)
        {
            //去掉入参前后空格
            ToolHelper.TrimStrings(input);

            // 获取操作用户的信息
            var user = TokenService.GetClaimKey() ?? throw Oops.Bah("未登录，无权限访问接口");

            var sen = await _db.Queryable<SensitiveWords>()
                .FirstAsync(it => it.Id == input.Id) ?? throw Oops.Bah("id错误【SetSensitiveWordsIsEnabled】");

            sen.IsEnabled = input.IsEnabled.Value;
            sen.UpdateMan = user.UserName;
            sen.UpdateTime = DateTime.Now;

            int count = await _db.Updateable(sen).WhereColumns(it => it.Id)
                .UpdateColumns(it => new
                {
                    it.IsEnabled,
                    it.UpdateMan,
                    it.UpdateTime
                }).ExecuteCommandAsync();
            if (count < 1)
            {
                throw Oops.Bah("设置失败");
            }

            return new ResponseStatus
            {
                StatusCode = 200,
                Message = $"设置敏感词【{sen.Word}】{(sen.IsEnabled ? "启用" : "禁用")}成功"
            };
        }

        /// <summary>
        /// 移除敏感词-批量
        /// </summary>
        /// <returns></returns>
        public async Task<ResponseStatus> DeleteSensitiveWords(DeleteSensitiveWordsInput input)
        {
            //去掉入参前后空格
            ToolHelper.TrimStrings(input);

            // 获取操作用户的信息
            var user = TokenService.GetClaimKey() ?? throw Oops.Bah("未登录，无权限访问接口");

            var sens = await _db.Queryable<SensitiveWords>()
                .Where(it => input.Ids.Contains(it.Id)).ToListAsync()
                ?? throw Oops.Bah("id有错误【DeleteSensitiveWords】");

            int count = await _db.Deleteable<SensitiveWords>()
                .Where(it => sens.Select(it => it.Id).Contains(it.Id)).ExecuteCommandAsync();
            if (count < 1)
            {
                throw Oops.Bah("移除失败");
            }

            return new ResponseStatus { StatusCode = 200, Message = $"已成功移除" };
        }
    }
}
